package com.xuan.commons.config.jwt;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author renzhengxuan
 * @date 2021/5/23
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            executeLogin(request,response);
            return true;
        } catch (Exception e) {
            throw new AuthenticationException("token失效，请重新登录",e);
        }
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        String token = httpServletRequest.getHeader("token");
        JwtToken jwtToken = new JwtToken(token);
//        将jwttoken交给realm进行登入，如果出现错误会抛出异常
        getSubject(request,response).login(jwtToken);
        return true;
    }
}
